import React, { useEffect } from 'react';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

interface TaskCompletedMessage {
    type: string;
    message: string;
    task_id: string;
    status: string;
    should_refresh: boolean;
}

const MarketDataWatcher = () => {
    useEffect(() => {
        // 建立WebSocket连接
        const socket = new WebSocket('ws://127.0.0.1:8001/ws/market/');
        let reconnectAttempts = 0;
        const maxReconnectAttempts = 5;
        const reconnectDelay = 3000; // 3秒
        
        const setupSocket = () => {
            socket.onopen = () => {
                console.log('WebSocket连接已建立');
                reconnectAttempts = 0; // 重置重连计数器
                
                // 心跳检测
                const heartbeatInterval = setInterval(() => {
                    if (socket.readyState === WebSocket.OPEN) {
                        socket.send(JSON.stringify({type: 'heartbeat'}));
                    }
                }, 30000); // 30秒一次心跳

                return () => clearInterval(heartbeatInterval);
            };

        socket.onmessage = (event) => {
            try {
                const data: TaskCompletedMessage = JSON.parse(event.data);
                console.log('data = ',data.message);
                console.log('收到任务完成消息')
                // 处理任务完成消息
                if (data.type === 'task_completed') {
                    toast.success(data.message, {
                        position: "top-right",
                        autoClose: 5000,
                        hideProgressBar: false,
                        closeOnClick: true,
                        pauseOnHover: true,
                        draggable: true,
                    });
                    
                    // 如果需要刷新数据
                    if (data.should_refresh) {
                        // 这里调用你的数据刷新逻辑
                        // 例如: refreshMarketData();
                        console.log('接收到数据刷新通知');
                    }
                }
            } catch (error) {
                console.error('处理WebSocket消息出错:', error);
            }
        };

        socket.onclose = (event) => {
            console.log('WebSocket连接关闭', event.code, event.reason);
            
            // 非正常关闭时尝试重连
            if (event.code !== 1000 && reconnectAttempts < maxReconnectAttempts) {
                const delay = Math.min(reconnectDelay * Math.pow(2, reconnectAttempts), 30000);
                console.log(`将在${delay/1000}秒后尝试第${reconnectAttempts + 1}次重连`);
                
                setTimeout(() => {
                    reconnectAttempts++;
                    setupSocket();
                }, delay);
            }
        };

        socket.onerror = (error) => {
            console.error('WebSocket错误:', error);
        };
    };

    return () => {
        // 正常关闭连接(1000)
        if (socket.readyState === WebSocket.OPEN) {
            socket.close(1000, '组件卸载');
        }
    };
}, []);

    return null; // 这个组件不需要渲染任何UI
};

export default MarketDataWatcher;